//
//  String+Extension.swift
//  zhengwutong
//
//  Created by wangshuguan on 16/8/22.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
extension Optional where Wrapped == String{
    var intValue : Int {
        get{
            return Int(self ?? "0") ?? 0
        }
    }
    var isNotEmpty:Bool{
        get{
            return !(self ?? "").isEmpty
        }
    }
}
extension String {
    func ranges(of searchString: String) -> [NSRange]{
        guard self.isNotEmpty else {
            return []
        }
        var ranges:[NSRange] = []
        
        for i in 0..<self.count {
            var r1 = NSString(string: self[i..<self.count]).range(of: searchString)
            if r1.length > 0{
                r1.location += i
                ranges.append(r1)
            }
        }
        return ranges
    }
    var htmlToString:String{
        get{
            do{
                let attr = try NSAttributedString(data: self.data(using: .unicode) ?? Data(), options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html], documentAttributes: nil)
                return attr.string
            }catch{
                return ""
            }
        }
    }
    /// 转换为剩余两位小数点的字符串
    var float2f:String{
        get{
            return String(format: "%.2f", Double(self)!)
        }
    }
    func toJsonObject() -> Any? {
        guard self.isNotEmpty else {
            return nil
        }
        var obj:Any?
        do{
            obj = try JSONSerialization.jsonObject(with: self.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions.allowFragments)
        }catch{
            ZWTPrint("不能转换成json对象")
        }
        return obj
    }
    func toAttribuiteString() -> NSAttributedString{
        return NSAttributedString(string:self)
    }
    func searchAttribuiteString(searchString:String,attr:[NSAttributedString.Key:Any]) -> NSAttributedString{
        let zhongbiaoText = NSMutableAttributedString(string: self)
        zhongbiaoText.addAttributes(attr, range: NSString(string: zhongbiaoText.string).range(of: searchString))
        return zhongbiaoText
    }
    func toUrlEncodeString() -> String? {
        return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed.union(CharacterSet.urlHostAllowed.union(CharacterSet.urlQueryAllowed)).union(CharacterSet(charactersIn: "%")))
    }
    func size(withAttributes attributes:[NSAttributedString.Key : Any]) -> CGSize {
        return NSString(string: self).size(withAttributes: attributes)
    }
    /// 分块儿
    /// - Parameter segment: 每块大小
    /// - Returns: 分块儿之后的数据集合
    public func split(_ size:Int)->[String]{
        guard size > 0 else {
            return [self]
        }
        var arr:[String] = []
        for i in 0..<self.count/size{
            arr.append(self[i*size..<(i+1)*size])
        }
        if self.count % size != 0 {
            arr.append(self[self.count/size*size..<self.count])
        }
        return arr
    }
    static func * (lhs: String, rhs: Int) -> Array<String>{
        var arr = Array<String>()
        for _ in 0..<rhs{
            arr.append(lhs)
        }
        return arr
    }
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return String(self[startIndex ..< endIndex])
        }
    }
    func replacingCharacters<T>(in range: Range<Int>, with replacement: T) -> String where T : StringProtocol{
        
        let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
        let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
        return replacingCharacters(in: startIndex..<endIndex, with: replacement)
    }
}
//检验类
extension String{
    var isNotEmpty:Bool{
        get{
            return !self.isEmpty
        }
    }
    var isNotEmptyOrBlank:Bool{
        get{
            return !self.isEmpty && !self.isBlank
        }
    }
    var isTelePhoneString : Bool{
        get{
            return self.range(of: "^1\\d{10}$", options: .regularExpression) != nil
        }
    }
    var isPointNumber:Bool{
        get{
            return self.range(of: "^-?[0-9]+(\\.[0-9]{1,})?$", options: .regularExpression) != nil
        }
    }
    var isUintPointNumber:Bool{
        get{
            return self.range(of: "^[0-9]+(\\.[0-9]{1,})?$", options: .regularExpression) != nil
        }
    }
    var isNumber:Bool{
        get{
            return self.range(of: "^-?[0-9]+$", options: .regularExpression) != nil
        }
    }
    var isAscII:Bool{
        get{
            return self.range(of: "^-?[a-zA-Z0-9]+$", options: .regularExpression) != nil
        }
    }
    var isUintNumber:Bool{
        get{
            return self.range(of: "^[0-9]+$", options: .regularExpression) != nil
        }
    }
    var isEmail:Bool{
        get{
            return self.range(of: "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$", options: .regularExpression) != nil
        }
    }
    var isBlank:Bool{
        get{
            return self.range(of: "^ +$", options: .regularExpression) != nil
        }
    }
    var isPassword:Bool{
        get{
            return self.range(of: "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$", options: .regularExpression) != nil
        }
    }
}
extension Dictionary{
    public func jsonString(options:JSONSerialization.WritingOptions = JSONSerialization.WritingOptions()) -> String? {
        var json:String?
        do{
            json = try String(data: JSONSerialization.data(withJSONObject: self as AnyObject, options: options), encoding: String.Encoding.utf8)
        }catch{
            fatalError("\(error)")
        }
        return json
    }
    var isNotEmpty:Bool{
        get{
            return !self.isEmpty
        }
    }
    public func nullToString() -> Dictionary<Key,Value> {
        var dic:[Key:Value] = [:]
        for (k,v) in self{
            dic[k] = v is NSNull ? "" as? Value : v
        }
        return dic
    }
}
extension Array{
    var isNotEmpty:Bool{
        get{
            return !self.isEmpty
        }
    }
    public func jsonString() -> String? {
        var json:String?
        do{
            json = try String(data: JSONSerialization.data(withJSONObject: self as AnyObject, options: JSONSerialization.WritingOptions()), encoding: String.Encoding.utf8)
        }catch{
            fatalError("\(error)")
        }
        return json
    }
    public func sub(_ begin:Int,_ lenth:Int = 0 )->Array{
        guard begin + lenth <= self.count else {
            fatalError("数组溢出")
        }
        
        var arr = Array()
        for index in begin..<begin+lenth {
            arr.append(self[index])
        }
        return arr
    }
    subscript (r: Range<Int>) -> Array {
        get {
            let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
            return sub(startIndex, endIndex-startIndex)
        }
    }
}
extension Dictionary where Key == String,Value == String{
    static func + <Key,Value>(lhs: Dictionary<Key,Value>, rhs: Dictionary<Key,Value>) -> Dictionary<Key,Value>{
        var arr = lhs
        for (k,v) in rhs {
            arr[k] = v
        }
        return arr
    }
}
extension Array where Element : Hashable{
    func withoutDuplicate() -> [Element]{
        var set:Set<Element> = []
        var arr:Array<Element> = []
        for x in self{
            let oldCount = set.count
            set.insert(x)
            if set.count>oldCount{
                arr.append(x)
            }
        }
        return arr
    }
    static func + <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Array<Element>{
        var arr = lhs
        arr.append(contentsOf: rhs)
        return arr
    }
}
extension Double{
    static func % (left:Double,right: Double)->Double{
        return left.truncatingRemainder(dividingBy: right)
    }
}
extension Set where Element : Hashable {
    public mutating func insert(contentsOf arr: [Set.Element]){
        for o in arr {
            self.insert(o)
        }
    }
}
/// 打印日志
/// - Parameters:
///   - string: 要打印的内容
///   - type: 0代表普通打印，1代表网络日志打印
func ZWTPrint(_ string:Any,type:Int = 0) {
    var l = LogDestination()
    if let s = string as? String{
        if ShareHandle.shared.writeLog{
            print(s, to: &l)
        }else{
            print("\(Date().description(string: "yyyy-MM-dd HH:mm:ss.SSS")):\(s)" )
        }
//
    }else{
        if ShareHandle.shared.writeLog{
            print("\(string)", to: &l)
        }else{
            print("\(Date().description(string: "yyyy-MM-dd HH:mm:ss.SSS")):\(string)")
        }
    }
}
final class LogDestination: TextOutputStream {
  private let path: String
  init() {
    let paths = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)
    path = paths.first! + "/Caches/log"
    if !FileManager.default.isWritableFile(atPath: path) {
        FileManager.default.createFile(atPath: path, contents: nil, attributes: nil)
    }
  }

  func write(_ string: String) {
    if let data = string.data(using: .utf8), let fileHandle = FileHandle(forWritingAtPath: path) {
      defer {
        fileHandle.closeFile()
      }
      fileHandle.seekToEndOfFile()
      fileHandle.write(data)
    }
  }
}

/// 处理金额字符串
extension String {
    
    /// 去除额外的0，小数点之后的0
    /// - Returns:
    func noneZeroString() -> String {

        var outNumStr = self
        var i = 1

        if self.contains(".") {
            while i < self.count {
                if outNumStr.hasSuffix("0") {
                    outNumStr.remove(at: outNumStr.index(before: outNumStr.endIndex))
                    i = i + 1
                } else {
                    break
                }
            }
            if outNumStr.hasSuffix(".") {
                outNumStr.remove(at: outNumStr.index(before: outNumStr.endIndex))
            }
            return outNumStr
        } else {
            return self
        }
    }
}
